package com.sylingd.blog.ui.adapter

import android.app.Fragment
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.sylingd.blog.R
import com.sylingd.blog.activity.ReadActivity
import com.sylingd.blog.bean.Article
import com.sylingd.blog.lib.Config
import java.text.SimpleDateFormat
import java.util.*



class ArticleAdapter(context: Context, resource: Int, private val fragment: Fragment)
	: RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {

	private var mInflater = LayoutInflater.from(context)
	private var mResource = resource
	private val items = ArrayList<Article>()

	override fun getItemCount(): Int = items.size

	override fun onBindViewHolder(holder: ViewHolder, position: Int) {
		val item = items[position]
		holder.date.text = items[position].formatDate("yyyy-MM-dd")
		holder.title.text = items[position].title

		//点击进入详情
		holder.self.setOnClickListener({
			ReadActivity.launch(fragment.activity, item.id, item.title)
		})
	}

	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
		val v = mInflater.inflate(mResource, parent, false)
		return ViewHolder(v)
	}

	fun add(item: Article) {
		items.add(item)
		notifyDataSetChanged()
	}

	fun getFirst(): Article? {
		return if (items.size > 0) items[0] else null
	}

	fun getLast(): Article? {
		return if (items.size > 0) items.last() else null
	}

	fun addToStart(item: Article) {
		items.add(0, item)
		notifyDataSetChanged()
	}

	fun isExists(id: Int): Boolean {
		items.forEach {
			if (it.id == id) {
				return true
			}
		}
		return false
	}
	fun isExists(item: Article): Boolean {
		return items.indexOf(item) >= 0
	}

	class ViewHolder(v: View): RecyclerView.ViewHolder(v) {
		val self: View = v
		val title: TextView = v.findViewById(R.id.articleTitle)
		val date: TextView = v.findViewById(R.id.articleDate)
	}

}